<?php

/* Copyright (c) 2007 Alec Henriksen
 * phpns is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public Licence (GPL) as published by the Free
 * Software Foundation; either version 2 of the Licence, or (at your option) any
 * later version.
 * Please see the GPL at http://www.gnu.org/copyleft/gpl.html for a complete
 * understanding of what this license means and how to abide by it.
*/

/* This file will need little to NO modification. All customization can be done 
before including the file, using pre-set variables. If you need to make modifications 
to this file, it's important to comment your code. This is obviously the most important
file in the system, so understanding it is important. All functions are defined here are 
seperate from the main system (for security reasons.)

-- Alec Henriksen (http://phpns.com | http://alecwh.com)
*/

/* Optional variables that can be called before user include:
   * $limit = 1-9999
   * $template = template_name
   * $category (multiple) = ID Number(s) (seperated by commas (cat1, cat2, cat3))
   * $mode (RSS) = RSS, XML, ATOM
   * $offset = 1-9999
*/

//define some variables, immediately protect against injection

	$do = htmlentities($_POST['do']);
	if (!$do) { $id = htmlentities($_SERVER['QUERY_STRING']); }
	$mode = htmlentities($mode);
	$offset = htmlentities($offset);
	
	//generate current time, used globally
	$time = time();
	$ip = $_SERVER['REMOTE_ADDR'];
	
	//default template id (0 for now)
	$default_template = 0;
	
//before continuing, protect from injection
if (!file_exists('.htaccess')) { //if there is no .htaccess, check to make sure $id is all good
	if (!is_numeric($id) && $id) {
		$inject_error = '
			<h1>security breach</h1>
			<hr />
			<strong>'.$id.'</strong>
			<p>Phpns has detected that you (or the link you used to get here) attempted to breach our database with a method called "injection". This is usually because the id variable contains a non-numeric character. If you think this message is a mistake, contact the system administrator.</p>

			<div><h5>Copyright 2007-08 Alec Henriksen | GPL License</h5></div>
		';
		die($inject_error);
	}
} else {
	$mod_rewrite = TRUE;
}
	
//include database information
	@require("inc/config.php");
//connect.
$mysql['connection'] = mysql_connect($databaseinfo['host'], $databaseinfo['user'], $databaseinfo['password'])
or die ($error['connection']);
//select mysql database
$mysql['db'] = mysql_select_db($databaseinfo['dbname'],$mysql['connection'])
or die ($error['database']);
	
//define show_news functions, and check if functions are already defined.
	if (!function_exists('clean_data')) {
		function clean_data($data) {
			if (is_array($data)) {
				foreach ($data as $key => $value) {
					if(ini_get('magic_quotes_gpc')) { $data[$key] = stripslashes($value); }
					$data[$key] = htmlspecialchars($value);
					}
			} else {
				if(ini_get('magic_quotes_gpc')) { $data = stripslashes($data); }
				$data = htmlspecialchars($data, ENT_QUOTES);
			}
			return $data;
		}
		function decode_data($data) {
			if (is_array($data)) {
				foreach ($data as $key => $value) {
					$data[$key] = htmlspecialchars_decode($value);
					}
			} else {
				$data = htmlspecialchars_decode($data);
			}
			return $data;
		}
		function db_fetch($query,$type,$clean=NULL) {
		
				if ($clean == TRUE) {
					$query = clean_data($query); //clean
				}
				
			$res = mysql_query($query) or die(mysql_error());
			//return value or not?
				if ($type == 1) { //if we want a value
					$value = mysql_fetch_array($res) or die("meh");
					return $value;
				} else {
					return $res;
				}
		}
		function db_insert($query) {
			//sql construction
			$insert_res = mysql_query($query) or die(mysql_error());
			$affected = mysql_affected_rows();
			return $affected;
		}
		function fetch_template() { //figure out default template, or use a user defined one.
			if (!$template) {  //if template is not defined by pre-var include... get default
				global $default_template;
				
				$sql = "SELECT * FROM templates WHERE template_selected='1' LIMIT 1";
				//after cleaning data, request
				$res = mysql_fetch_array(mysql_query($sql));
					//update default_template var
					$default_template = $res['id'];
				return $res; //return default template (changeable in preferences)
			} else {
				$sql = "SELECT * FROM templates WHERE id=".$template." LIMIT 1";
				$res = mysql_fetch_array($sql);
				return $res;
			}
		}
		function translate_item($item,$template,$type) {
			global $id;
			/* 
			HTML_ARTICLE:
				{title} = article title
				{subtitle} = subtitle
				{date} = timestamp/date
				{main_article} = main article
				{full_story} = full story
				{author} = author
				{article_href} = the link to the article, but the actual href value
				{reddit} = reddit social networking link
				{digg} = digg social networking link
				{del.icio.us} = del.icio.us social networking link
			HTML_COMMENT
				{author} = comment author
				{website} = website
				{comment} = comment
				{date} = comment date
				{ip} = comment ip address
			HTML_FORM:
				{action} = value that goes inside the <form>
				{hidden_data} = required value somewhere inside the <form>
				
			*/
			global $timestamp_format;
			$template = decode_data($template);
			if ($type == "html_article") { //if we are working with the html_article
					//change back from htmlspecialchars to htmlspecialchars_decode, and define some other vars
					$item = decode_data($item);
					$item['timestamp'] = date($timestamp_format['v3'], $item['timestamp']);
					$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$item['id'];

				$template = str_replace('{title}', $item['article_title'], $template);
				$template = str_replace('{subtitle}', $item['article_subtitle'], $template);
				$template = str_replace('{main_article}', $item['article_text'], $template);
				if ($id) { $template = str_replace('{full_story}', $item['article_exptext'], $template); } else { $template = str_replace('{full_story}', '', $template); }
				$template = str_replace('{date}', $item['timestamp'], $template);
				$template = str_replace('{author}', $item['article_author'], $template);
				
				//construct href for a
				$template = str_replace('{article_href}', '?'.$item['id'], $template);
				
				//reddit, digg, del.icio.us buttons
				$template = str_replace('{reddit}', '
				<script>reddit_url=\''.$url.'\'</script>
				<script>reddit_title=\''.$item['article_title'].'\'</script>
				<script language="javascript" src="http://reddit.com/button.js?t=2"></script>
				', $template);
				
				//digg_url = \''.$url.'\'; is the real one
				$template = str_replace('{digg}', '
				<script type="text/javascript">
					digg_url = \'http://purple.com/\';
				</script>
				<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script> 
				', $template);
				$template = str_replace('{del.icio.us}', '', $template);
					//comment numeric representations
					$comment_num = db_fetch('SELECT COUNT(*) FROM comments WHERE article_id='.$item['id'].'',1,FALSE);
					$template = str_replace('{comment_count}', $comment_num[0], $template);
				return $template;	
			} elseif ($type == "html_comment") {
				$item['timestamp'] = date($timestamp_format['v3'], $item['timestamp']);
				$item['comment_text'] = nl2br($item['comment_text']);
				$template = str_replace('{author}', $item['comment_author'], $template);
				$template = str_replace('{timestamp}', $item['timestamp'], $template);
				$template = str_replace('{comment}', $item['comment_text'], $template);
				$template = str_replace('{website}', $item['website'], $template);
				$template = str_replace('{ip}', $item['ip'], $template);
				return $template;
				
				
			} elseif ($type == "html_form") {
				//start translation for the html comment form
				$template = str_replace('{action}', '?'.$id.'', $template);
				$template = str_replace('{hidden_data}', '<input type="hidden" name="id" value="'.$id.'" />', $template);
				return $template;
			}
			
			
		}
	}
	
		//timestamp format fetch
		$timestamp_format = db_fetch("SELECT * FROM gconfig WHERE name='timestamp_format'",1,FALSE);
		$template = fetch_template(); //fetch template. :)  // echo $default_template;
		

	//before anything else, we're going to detect if there is post data, and if there is, we'll insert the db. If there is no post data, just pass over this.
	//Let it be known, that I, Kyle, fixed this for Alec, because he didn't know how to make it work ;)
	       if ($_POST) {
                //IF THERE IS POST DATA, then we're submitting the form. We need to clean data.
                $comment['name'] = clean_data($_POST['name']);
                $comment['email'] = clean_data($_POST['email']);
                $comment['website'] = clean_data($_POST['website']);
                $comment['comment'] = clean_data($_POST['comment']);
                $comment['id'] = clean_data($_POST['id']);

                        //if comment_id is not numeric, kill with message
                        if (!is_numeric($comment['id'])) { die("non-numeric form id, invalid information."); }
                                $insert = db_insert('
                                        INSERT INTO comments (article_id,comment_text,comment_author,website,timestamp,approved,ip) VALUES ("'.$comment['id'].'","'.$comment['comment'].'","'.$comment['name'].'","'.$comment['website'].'","'.$time.'","1","'.$ip.'")');
 		}

	if (!$do && !$mode && !$id) { //if no defined action, show news as it is meant to be displayed.

		//gather some important variables from db.
		if ($category) { $category = "WHERE article_cat IN ($category,'all')"; }
		if (!$offset) { $offset = db_fetch("SELECT * FROM gconfig WHERE name='def_offset'",1); }
		if (!$limit) { $limit = db_fetch("SELECT * FROM gconfig WHERE name='def_limit'",1); }
		if (!$order) { $order = db_fetch("SELECT * FROM gconfig WHERE name='def_order'",1); }
		

		//forming actual news query.	
		$fetch_news_sql = "
			SELECT * FROM articles
			".$category."
			WHERE
			active='1' AND approved='1'
			ORDER BY timestamp ".$order['v1']."
			LIMIT ".$offset['v1'].",".$limit['v1']."
			";
		$fetch_news_res = mysql_query($fetch_news_sql) or die(mysql_error());
		
		while ($row = mysql_fetch_assoc($fetch_news_res)) {  //start fetch loop
			
			if ($time >= $row['start_date'] || $time <= $row['end_date']  || $row['start_date'] == NULL || $row['end_date'] == NULL) {
				$returned_data = translate_item($row, $template['html_article'], 'html_article'); //translate into template
				$content .= $returned_data;
			}
		}
	} elseif ($id) {
		if (!$override) { $allow_com = db_fetch("SELECT * FROM gconfig WHERE name='def_comenabled'",1); } else { $allow_com = TRUE; }
		//forming actual news query.	
		$fetch_news_sql = "
			SELECT * FROM articles
			WHERE
			active='1' AND approved='1' AND id='".$id."' LIMIT 1
			";
		$fetch_news_res = mysql_query($fetch_news_sql) or die(mysql_error());
		while ($row = mysql_fetch_assoc($fetch_news_res)) {  //start fetch loop
			if ($time >= $row['start_date'] || $time <= $row['end_date']  || $row['start_date'] == NULL || $row['end_date'] == NULL) { //if we're set for time landings
				$allow_com['article_specific'] = $row['allow_comments'];
				$returned_data = translate_item($row, $template['html_article'], 'html_article'); //translate into template
				$content .= $returned_data;
			}
			
		}
		//echo var_dump($allow_com); //debug
		//now, we generate comments for this specific article IF they are enabled
		if ($allow_com['v1'] == TRUE) {
			$fetch_com_sql = "SELECT * FROM comments WHERE article_id='".$id."' AND approved='1'";
			$fetch_com_res = mysql_query($fetch_com_sql) or die(mysql_error());
				//for each row (or comment) generated, we translate the item and assign it to $content
				while ($row = mysql_fetch_assoc($fetch_com_res)) {
					$comment_list .= translate_item($row, $template['html_comment'], 'html_comment');
				}
		}
			//assign $comment_list to $content
			$content .= $comment_list;
		
		//translate html comment form, then add it to the end of $content, if comments are enabled
		if ($allow_com['v1'] == TRUE && $allow_com['article_specific'] == 1) {
			$form_template = translate_item('', $template['html_form'], 'html_form');
		} else {
			$form_template = '<span class="comments_are_disabled">Comments are disabled for this article.</span>';
		}
			//add it to $content ($form_template will be empty if comments are not enabled)
			$content .= '
			'.$form_template;
	} //end main if
	
	// echo var_dump($allow_com); //debugging, keep commented.
	
if ($id == -42) { //phpns easter egg (erase if you want). hehe. :)
	$globalvars['page_name'] = " ";
	$globalvars['page_image'] = ' ';
	$content = '
	<p>I thought this would be fun. If I get sent enough hate mail, I\'ll gladly remove it. - <em><a href="http://alecwh.com">Alec Henriksen</a></em></p>
	<blockquote>
		"I think the problem is that the question was too broadly based..."<br /><br />
"Forty two?!" yelled Loonquawl. "Is that all you\'ve got to show for seven and a half million years\' work?"<br /><br />
"I checked it very thoroughly," said the computer, "and that quite definitely is the answer. I think the problem, to be quite honest with you, is that you\'ve never actually known what the question is."<br /><br />
		<strong>Douglas Adams. The Hitchhiker\'s Guide to the Galaxy</strong>
	</blockquote> 
	';
}
	
	echo $content; //and... finally post the content
	
?>
